package com.zhaungwei.weather.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaungwei.weather.service.WeatherDataService;
import com.zhaungwei.weather.vo.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * @author LeviCoder
 * @create 2019-03-21 0:07
 */
@Slf4j
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";
    private static final Long TIME_OUT = 18000L;

    @Override
    public WeatherResponse getDataByCity(String city) {
        String url = WEATHER_URL + "city=" + city;

        return doGet(url);
    }

    @Override
    public WeatherResponse getDataBycitykey(String citykey) {
        String url = WEATHER_URL + "citykey=" + citykey;

        return doGet(url);
    }

    /**
     * 共同调用此方法：实现代码的重构
     */
    private WeatherResponse doGet(String url) {

        ObjectMapper objectMapper = new ObjectMapper();
        WeatherResponse resp = null;
        String strBody = null;

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

        // 先查缓存，缓存有的取缓存中的数据
        if (stringRedisTemplate.hasKey(url)) {
            log.info("Redis has date");
            strBody = ops.get(url);
        } else {
            log.info("Redis don't has date");
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if (responseEntity.getStatusCodeValue() == 200) {
                strBody = responseEntity.getBody();
            }
            // 数据写入缓存
            ops.set(url,strBody,TIME_OUT,TimeUnit.SECONDS);
        }

        try {
            resp = objectMapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resp;
    }

    @Override
    public void syncDateByCitykey(String citykey) {
        String uri = WEATHER_URL + "citykey=" + citykey;
        this.saveWeatherData(uri);
    }

    /**
     * 把天气数据放在缓存
     * @param uri
     */
    private void saveWeatherData(String uri) {
        String strBody = null;
        ValueOperations<String, String>  ops = stringRedisTemplate.opsForValue();

        // 调用服务接口来获取
        ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        // 数据写入缓存
        ops.set(uri, strBody, TIME_OUT, TimeUnit.SECONDS);

    }
}
